//
//  ProductListViewController.m
//  CenturyInterconnection
//
//  Created by Tian Wei You on 16/4/8.
//  Copyright © 2016年 Shanghai DuRui Information Technology Company. All rights reserved.
//

#import "ProductListViewController.h"
#import "HomepageCollectionViewCell.h"
#import "CommodityDetailsTableViewController.h"
#import "UIScrollView+MJRefresh.h"

#define HomepageCell  @"HomepageCollectionViewCell"

@interface ProductListViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,SlideNavigationControllerDelegate>

@property(nonatomic,strong) UICollectionView * collectionView;
@property(nonatomic,strong) NSMutableArray * allDatas;
@property(nonatomic,assign) NSInteger pagenumber;

@end

@implementation ProductListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if(self.categories_name){
        self.title = self.categories_name;
    }else{
        self.title=self.ListOfSpeciesStr;
    }
    
    self.view.backgroundColor=[UIColor whiteColor];
    
    self.allDatas=[NSMutableArray array];
    
    self.pagenumber=1;
    
    [self getDatas];
    
    [self makeNaviButton];

    [self makeView];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
        
    [MobClick beginLogPageView:[NSString stringWithFormat:@"ProductListPage >>> %@",self.categories_name]];//("PageOne"为页面名称，可自定义)
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:[NSString stringWithFormat:@"ProductListPage >>> %@",self.categories_name]];
}




#pragma mark - 导航栏

-(void)makeNaviButton{
    
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [leftButton setBackgroundImage:[UIImage imageNamed:@"nav_back"] forState:0];
    leftButton.frame=CGRectMake(0, 0, ACTUAL_WIDTH(23), ACTUAL_HEIGHT(23));
    [leftButton addTarget:self action:@selector(comeBack) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem*item=[[UIBarButtonItem alloc]initWithCustomView:leftButton];
    self.navigationItem.leftBarButtonItem=item;
}


#pragma mark - 返回事件
-(void)comeBack{
    [self.navigationController  popViewControllerAnimated:YES];
}

#pragma mark - getDatas
-(void)getDatas{
    
    NSDictionary * paramss = [[NSDictionary alloc] init];
    
    if ([self.ListOfSpeciesStr isEqualToString:@"products_new"]) {
    
        // http://viprunningonline.com/api/index.php?main_page=products_new
        paramss=@{@"main_page":@"products_new",
                  @"page":[NSString stringWithFormat:@"%ld",(long)self.pagenumber]};
        [self allDataRequest:paramss withTitle:nil];
        
        return;
    }
    
    if ([self.ListOfSpeciesStr isEqualToString:@"featured_products"]){
        
        // http://viprunningonline.com/api/index.php?main_page=featured_products
        paramss=@{@"main_page":@"featured_products",
                  @"page":[NSString stringWithFormat:@"%ld",(long)self.pagenumber]};
        
        [self allDataRequest:paramss withTitle:nil];
        
        return;
    }
        
    if ([self.ListOfSpeciesStr isEqualToString:@"products_list"]){
        
        // http://viprunningonline.com/api/index.php?main_page=products_list
        paramss=@{@"main_page":@"products_list",
                  @"cPath":self.cPathStr,
                  @"page":[NSString stringWithFormat:@"%ld",(long)self.pagenumber]};
        
        [self allDataRequest:paramss withTitle:nil];
        
        return;
    }
}



- (void)allDataRequest:(NSDictionary *) paramss withTitle:(NSString *)titleString
{
     NSString*urlStrr=[NSString stringWithFormat:@"%@",HTTP_ADDRESS];
    HttpManager*managerr=[[HttpManager alloc]init];
    [managerr getDataFromNetworkWithUrl:urlStrr parameters:paramss compliation:^(id data, NSError *error) {
    
        [self endRefresh];
        NSString*number=[NSString stringWithFormat:@"%@",data[@"status"]];
        
        if ([number isEqualToString:@"1"]) {
            
            if ([data[@"data"] count] <= 0) {
                [JRToast showWithText:data[@"No data"] duration:2.0];
                return ;
            }
            
            if (self.pagenumber <= [data[@"data"][@"total_pages"] intValue]) {
                [self.allDatas addObjectsFromArray:data[@"data"][@"products_list"] ];
                [self.collectionView reloadData];
                
            }else{
                [JRToast showWithText:@"finsh download data" duration:2.0];
            }
            
        }else{
            [JRToast showWithText:data[@"status_message"] duration:2.0];
        }
        
    }];
}


#pragma mark -  makeView
-(void)makeView{
    
    UICollectionViewFlowLayout * flowLayout=[[UICollectionViewFlowLayout alloc]init];
//        flowLayout.scrollDirection=UICollectionViewScrollDirectionVertical;
    flowLayout.minimumLineSpacing=10;
    flowLayout.minimumInteritemSpacing=0;
    flowLayout.itemSize=CGSizeMake(ACTUAL_WIDTH(175), ACTUAL_HEIGHT(240));
    flowLayout.sectionInset=UIEdgeInsetsMake(ACTUAL_HEIGHT(0), ACTUAL_WIDTH(8), ACTUAL_HEIGHT(0), ACTUAL_WIDTH(8));
    
    
    UICollectionView * collectionView=[[UICollectionView alloc]initWithFrame:CGRectMake(0,0, KScreenWidth,KScreenHeight) collectionViewLayout:flowLayout];
    collectionView.showsHorizontalScrollIndicator=NO;
    collectionView.showsVerticalScrollIndicator=NO;
    collectionView.delegate=self;
    collectionView.dataSource=self;
    collectionView.scrollEnabled=YES;
    [collectionView registerNib:[UINib nibWithNibName:HomepageCell bundle:nil] forCellWithReuseIdentifier:HomepageCell];
    collectionView.backgroundColor=[UIColor whiteColor];
    self.collectionView=collectionView;
    self.collectionView.alwaysBounceVertical = YES;
    
    [self.view addSubview:collectionView];
    
    __unsafe_unretained typeof(self) vc = self;
    [self.collectionView addHeaderWithCallback:^{
        vc.pagenumber = 1;
        [vc.allDatas removeAllObjects];
        [vc getDatas];
        
    }];
    
    [self.collectionView addFooterWithCallback:^{
        vc.pagenumber ++ ;
        [vc getDatas];
    }];
}


#pragma mark - collectionView
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.allDatas.count;
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

-(UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    HomepageCollectionViewCell * cell=[collectionView dequeueReusableCellWithReuseIdentifier:HomepageCell forIndexPath:indexPath];
    
    cell.autoresizesSubviews = YES;
    cell.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin;
    cell.backgroundColor = [UIColor whiteColor];
    if(self.allDatas.count > 0){
        
        UIImageView *imageView=[cell viewWithTag:1];
        [imageView sd_setImageWithURL:[NSURL URLWithString:self.allDatas[indexPath.item][@"products_image"]] placeholderImage:nil];
        
        UILabel *label1=[cell viewWithTag:2];
        label1.text=self.allDatas[indexPath.item][@"products_name"];
        label1.font = FONT_SYSTEM_24;
        
        UILabel *label2=[cell viewWithTag:3];
        label2.text=self.allDatas[indexPath.item][@"products_price"];
        label2.font = FONT_SYSTEM_28;
    }
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dict = @{@"index" : self.allDatas[indexPath.item][@"products_name"]};
    [MobClick event:@"ProductListClick" attributes:dict];
    CommodityDetailsTableViewController *vc=[[CommodityDetailsTableViewController alloc]init];
    vc.idStr=self.allDatas[indexPath.item][@"products_id"];
    
    vc.imgUrlStr = self.allDatas[indexPath.item][@"products_image"];

    [self.navigationController pushViewController:vc animated:YES];
}


//#pragma mark - 刷新
//- (void)addHeader
//{
//    __unsafe_unretained typeof(self) vc = self;
//    // 添加下拉刷新头部控件
//    [self.collectionView addHeaderWithCallback:^{
//        vc.pagenumber=0;
//        vc.allDatas=[NSMutableArray array];
//        
//        [vc getDatas];
//        
//    } dateKey:@"collection"];
//    // dateKey用于存储刷新时间，也可以不传值，可以保证不同界面拥有不同的刷新时间
//    
//    #warning 自动刷新(一进入程序就下拉刷新)
//    [self.collectionView headerBeginRefreshing];
//}
//
//- (void)addFooter
//{
//    __unsafe_unretained typeof(self) vc = self;
//    // 添加上拉刷新尾部控件
//    [self.collectionView addFooterWithCallback:^{
//        vc.pagenumber++;
//        
//        // 进入刷新状态就会回调这个Block
//        [vc getDatas];
//        
//        // 模拟延迟加载数据，因此2秒后才调用（真实开发中，可以移除这段gcd代码）
//        
//    }];
//}


#pragma mark - endRefresh
- (void)endRefresh{
    
    [self.collectionView headerEndRefreshing];
    [self.collectionView footerEndRefreshing];
}

- (BOOL)slideNavigationControllerShouldDisplayRightMenu
{
    return YES;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
